package com.hthy.futures;

import android.app.Application;
import android.content.Context;

import com.franmontiel.persistentcookiejar.ClearableCookieJar;
import com.franmontiel.persistentcookiejar.PersistentCookieJar;
import com.franmontiel.persistentcookiejar.cache.SetCookieCache;
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor;
import com.google.gson.Gson;
import com.hthy.futures.api.SocketTradeManager;
import com.hthy.futures.bean.AppConfigContext;
import com.hthy.futures.bean.AppVersion;
import com.hthy.futures.utils.FileUtils;
import com.hthy.futures.utils.LogUtils;
import com.hthy.futures.utils.SPUtils;
import com.hthy.futures.utils.ToastUtil;
import com.vilyever.socketclient.SocketClient;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.https.HttpsUtils;
import com.zhy.http.okhttp.log.LoggerInterceptor;

import org.acra.ACRA;
import org.acra.ReportField;
import org.acra.annotation.ReportsCrashes;

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.OkHttpClient;

/**
 * Author:  Mr.bingley
 * Version:
 * Date:  2017/3/17
 */
@ReportsCrashes(
        reportSenderFactoryClasses = {com.hthy.futures.acra.YourOwnSenderfactory.class},  // 是.class
        customReportContent = {ReportField.APP_VERSION_CODE, ReportField.APP_VERSION_NAME, ReportField.ANDROID_VERSION, ReportField.PHONE_MODEL, ReportField.CUSTOM_DATA, ReportField.STACK_TRACE, ReportField.LOGCAT},
        resToastText = R.string.msg_acra_toast
)
public class AppContext extends Application {
    static Context _context;


    public static int accountId;
    public static String sessionId;
    public static String accountName;  // 用戶名
    public static String shareIp;

    public static String account;  // 登录名
    public static String accountPwd; // 账户密码


    public static String tradeIp;    // 交易ip
    public static int tradePort;  // 交易中心 port
    public static String quoteIp;   // 行情ip
    public static int quotePort; // 行情port


    public static String appversion; // 系统版本
    public static int appCode; // 系统版本号
    public static String appDowloadUrl; // 新版本下载地址

    private static SocketClient socketClient;

    public static List<AppConfigContext.ServerTypeBean> server_type;

    public static String defaultServiceName;  // 默认的服务器名字

    // 切换的时候要注意，除了在这里切换外， 版本号(build文件中去修改)  ，然后选择打包的方式。自己的版本就是界面不一樣而已,
    public static boolean tongnanEnv = false;    // true 代表同南，false 代表自己版本

    public static boolean isMarket = true;

    @Override
    public void onCreate() {
        ACRA.init(this);
        super.onCreate();
        _context = getApplicationContext();

        // log 开关 ，在正式发版时记得关闭
        LogUtils.DEBUG = true;


        // initAppConfig();

        // 初始化交易的socket
        //initSTradeSocket();

        initOKhttp();

    }

    /**
     * 初始化系統的配置（交易以及行情相关的配置、还有版本信息）
     */
    private void initAppConfig() {
        try {
            /*String configJson = FileUtils.getJson(this, "1234.config.json");
            AppConfig appConfig = createGson().fromJson(configJson, AppConfig.class);
            List<AppConfig.TradeGateBean> trade_gate = appConfig.getTrade_gate();
            AppConfig.TradeGateBean tradeGateBean = trade_gate.get(0);
            String tradeAddress = tradeGateBean.getAddr();
            String[] tradeSplit = tradeAddress.split(":");
            tradeIp = tradeSplit[0];
            tradePort = Integer.parseInt(tradeSplit[1]);

            List<AppConfig.QuoteGateBean> quote_gate = appConfig.getQuote_gate();
            AppConfig.QuoteGateBean quoteGateBean = quote_gate.get(0);
            String quoteAddress = quoteGateBean.getAddr();
            String[] quoteSplit = quoteAddress.split(":");
            quoteIp = quoteSplit[0];
            quotePort = Integer.parseInt(quoteSplit[1]);*/


            String versionJson = FileUtils.getJson(this, "1234.version.json");
            AppVersion appVersion = createGson().fromJson(versionJson, AppVersion.class);
            appversion = appVersion.getVersion();
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.show("解析的配置文件有错误");
        }
    }

    /**
     * 初始化交易的socket
     */
    public static void initSTradeSocket() {
        SocketTradeManager socketTradeManager = new SocketTradeManager();
        socketClient = socketTradeManager.getLocalSocketClient();
        socketTradeManager.connect(socketClient);
    }


    public static synchronized AppContext context() {
        return (AppContext) _context;
    }


    public SocketClient getSocketClient() {
        return socketClient;
    }


    public static Gson createGson() {
        com.google.gson.GsonBuilder gsonBuilder = new com.google.gson.GsonBuilder();
        return gsonBuilder.create();
    }

    /**
     * initokhttp ,并且配置https
     */
    private void initOKhttp() {
        ClearableCookieJar cookieJar1 = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getApplicationContext()));

        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);

//        CookieJarImpl cookieJar1 = new CookieJarImpl(new MemoryCookieStore());
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10000L, TimeUnit.MILLISECONDS)
                .readTimeout(10000L, TimeUnit.MILLISECONDS)
                .addInterceptor(new LoggerInterceptor("TAG"))
                .cookieJar(cookieJar1)
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                })
                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                .build();
        OkHttpUtils.initClient(okHttpClient);

    }

    /**
     * 统一解析配置文件处理
     *
     * @param response
     */
    public static void parseJson(String response) {
        try {
            AppConfigContext appConfigContext = AppContext.createGson().fromJson(response, AppConfigContext.class);
            server_type = appConfigContext.getServer_type();
            shareIp = appConfigContext.getRegister();
            appCode = appConfigContext.getVersionCode();
            appDowloadUrl = appConfigContext.getDownload();
            isMarket = appConfigContext.isMarket();
            AppConfigContext.ServerTypeBean serverTypeBean = server_type.get(0);

            SPUtils.saveToPrefs(AppContext.context(), AppConfig.logo ,appConfigContext.getLogo_uri());
            if (serverTypeBean != null) {
                setContextAddress(serverTypeBean);
            }
        } catch (Exception e) {
            ToastUtil.show("配置文件有误");
        }
        initSTradeSocket();
    }

    public static void setContextAddress(AppConfigContext.ServerTypeBean serverTypeBean) {
        defaultServiceName = serverTypeBean.getName();

        String trade_gate = serverTypeBean.getTrade_gate();
        String[] tradeSplit = trade_gate.split(":");
        AppContext.tradeIp = tradeSplit[0];
        AppContext.tradePort = Integer.parseInt(tradeSplit[1]);
        AppContext.tradePort = 8311;

        String quote_gate = serverTypeBean.getQuote_gate();
        String[] quoteSplit = quote_gate.split(":");
        AppContext.quoteIp = quoteSplit[0];
        AppContext.quotePort = Integer.parseInt(quoteSplit[1]);
    }

    /**
     * 从选择服务商那边获取的交易信息
     *
     * @param appConfigContext
     */
    public static void setNewService(AppConfigContext appConfigContext) {
        server_type = appConfigContext.getServer_type();
        shareIp = appConfigContext.getRegister();
        appCode = appConfigContext.getVersionCode();
        appDowloadUrl = appConfigContext.getDownload();
        AppConfigContext.ServerTypeBean serverTypeBean = server_type.get(0);

        if (serverTypeBean != null) {
            setContextAddress(serverTypeBean);
        }
        initSTradeSocket();
    }
}
